<template>
  <div class="product-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-shopping"></i>
        商品管理
      </h2>
      <p class="page-description">管理您的商品信息。商品状态由库存自动控制：库存>0自动上架允许购买，库存=0自动下架禁止购买</p>
    </div>

    <!-- 自动化状态说明 -->
    <div class="info-section">
      <el-alert
        title="商品状态自动管理"
        type="info"
        show-icon
        :closable="false">
        <div slot>
          <p>• 商品上架/下架状态由库存数量自动控制，无需手动操作。库存大于0时自动上架允许用户购买，库存为0时自动下架禁止用户购买。</p>
          <p>• 轮播图功能：通过开关可将上架商品添加到APP首页轮播展示，下架商品不可设置为轮播。</p>
        </div>
      </el-alert>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入商品名称"
              clearable
              style="width: 200px">
            </el-input>
          </el-form-item>
          <el-form-item label="上架时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 240px">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <el-card>
        <div slot="header" class="card-header">
          <span>商品列表</span>
          <div class="header-actions">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd">
              添加商品
            </el-button>
            <el-button
              icon="el-icon-refresh"
              @click="loadData">
              刷新
            </el-button>
          </div>
        </div>

        <configurable-table
          :columns="tableColumns"
          :data="productList"
          :loading="loading"
          :show-pagination="true"
          :current-page.sync="pagination.current"
          :page-size.sync="pagination.size"
          :pagination-total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          stripe
          :row-class-name="getRowClassName"
          @page-change="handlePageChange">
          <!-- 库存数量列 -->
          <template #num="{ row }">
            <span :class="{ 'zero-stock': row.num === 0 }">
              {{ row.num }}
            </span>
            <el-tag v-if="row.num === 0" type="danger" size="mini" style="margin-left: 5px;">
              缺货
            </el-tag>
          </template>

          <!-- 状态列 -->
          <template #status="{ row }">
            <el-tag :type="getStatusType(row.status, row.num)">
              {{ getStatusText(row.status, row.num) }}
            </el-tag>
          </template>

          <!-- 轮播图列 -->
          <template #carousel="{ row }">
            <el-switch
              v-model="row.isCarousel"
              :active-value="1"
              :inactive-value="0"
              :disabled="row.status !== 1"
              @change="handleCarouselChange(row)">
            </el-switch>
          </template>

          <!-- 操作列 -->
          <template #actions="{ row }">
            <el-button
              type="text"
              size="small"
              @click="handleView(row)">
              查看
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleEdit(row)">
              编辑
            </el-button>
          </template>
        </configurable-table>
      </el-card>
    </div>

    <!-- 商品详情对话框 -->
    <el-dialog
      title="商品详情"
      :visible.sync="detailDialogVisible"
      width="700px"
      custom-class="view-dialog"
      :close-on-click-modal="false">

      <div v-if="selectedProduct" class="detail-content">
        <!-- 状态横幅 -->
        <div
          :class="['status-banner', selectedProduct.num === 0 ? 'status-rejected' : 'status-success']">
          <div class="status-icon">
            <i :class="selectedProduct.num === 0 ? 'el-icon-close' : 'el-icon-success'"></i>
          </div>
          <div class="status-info">
            <div class="status-label">商品状态</div>
            <div class="status-value">
              {{ getStatusText(selectedProduct.status, selectedProduct.num) }}
              <span style="font-size: 14px; margin-left: 8px; opacity: 0.8;">
                {{ selectedProduct.num === 0 ? '（库存为0，自动下架）' : '（库存充足，自动上架）' }}
              </span>
            </div>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-goods"></i>
            <span>基本信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-document"></i>
                  商品ID
                </div>
                <div class="info-value">{{ selectedProduct.id }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-shopping-bag-1"></i>
                  商品名称
                </div>
                <div class="info-value">{{ selectedProduct.name }}</div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-coin"></i>
                  商品价格
                </div>
                <div class="info-value">
                  <span class="highlight-number">¥{{ formatPrice(selectedProduct.price) }}</span>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-box"></i>
                  库存数量
                </div>
                <div class="info-value">
                  <span :class="{ 'zero-stock': selectedProduct.num === 0 }">
                    {{ selectedProduct.num }}
                  </span>
                  <el-tag
                    v-if="selectedProduct.num === 0"
                    type="danger"
                    size="mini"
                    style="margin-left: 8px;">
                    缺货
                  </el-tag>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="info-row">
            <el-col :span="24">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-edit-outline"></i>
                  商品属性
                </div>
                <div class="info-value">{{ selectedProduct.attribute || '-' }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 时间信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-time"></i>
            <span>时间信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-upload2"></i>
                  上架时间
                </div>
                <div class="info-value">{{ formatDateTime(selectedProduct.createTime) }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-refresh"></i>
                  更新时间
                </div>
                <div class="info-value">{{ formatDateTime(selectedProduct.updateTime) }}</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">
          <i class="el-icon-close"></i>
          关闭
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑商品对话框 -->
    <el-dialog
      title="编辑商品"
      :visible.sync="editDialogVisible"
      width="650px"
      custom-class="action-dialog"
      :close-on-click-modal="false">

      <!-- 表单区域 -->
      <div class="form-section">
        <div class="section-title">
          <i class="el-icon-edit"></i>
          <span>商品信息</span>
        </div>

        <el-form
          :model="editForm"
          :rules="editRules"
          ref="editForm"
          label-width="120px"
          class="action-form">
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="editForm.name"
              placeholder="请输入商品名称"
              maxlength="50"
              show-word-limit>
            </el-input>
          </el-form-item>

          <el-form-item label="商品价格" prop="price">
            <div class="input-wrapper">
              <el-input-number
                v-model="editForm.price"
                :min="1"
                :max="999999"
                :precision="2"
                controls-position="right"
                style="width: 100%">
              </el-input-number>
              <div class="percentage-badge primary-badge">
                <i class="el-icon-coin"></i>
                单位：分
              </div>
            </div>
            <div class="form-tip">
              <i class="el-icon-info"></i>
              价格单位为分，例如：1000分 = 10.00元
            </div>
          </el-form-item>

          <el-form-item label="库存数量" prop="num">
            <div class="input-wrapper">
              <el-input-number
                v-model="editForm.num"
                :min="0"
                :max="999999"
                controls-position="right"
                style="width: 100%">
              </el-input-number>
              <div
                :class="['percentage-badge', editForm.num === 0 ? 'warning-badge' : 'success-badge']">
                <i :class="editForm.num === 0 ? 'el-icon-warning' : 'el-icon-success'"></i>
                {{ editForm.num === 0 ? '缺货' : '充足' }}
              </div>
            </div>
            <div class="form-tip">
              <i :class="editForm.num === 0 ? 'el-icon-warning' : 'el-icon-success'"></i>
              <span :style="{ color: editForm.num === 0 ? '#F56C6C' : '#67C23A' }">
                {{ editForm.num === 0 ? '库存为0时商品将自动下架，用户无法购买' : '库存充足，商品将自动上架，用户可购买' }}
              </span>
            </div>
          </el-form-item>

          <el-form-item label="商品属性" prop="attribute">
            <el-input
              v-model="editForm.attribute"
              type="textarea"
              :rows="3"
              placeholder="请输入商品属性描述，如：规格、颜色、尺寸等"
              maxlength="200"
              show-word-limit>
            </el-input>
            <div class="form-tip">
              <i class="el-icon-edit-outline"></i>
              可填写商品的规格、颜色、尺寸等属性信息
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">
          <i class="el-icon-close"></i>
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmitEdit" :loading="editLoading">
          <i class="el-icon-check"></i>
          {{ editLoading ? '保存中...' : '保存' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 添加商品对话框 -->
    <el-dialog
      title="添加商品"
      :visible.sync="addDialogVisible"
      width="900px"
      custom-class="action-dialog"
      :close-on-click-modal="false"
      @close="handleAddDialogClose">

      <!-- 基本信息区域 -->
      <div class="form-section">
        <div class="section-title">
          <i class="el-icon-goods"></i>
          <span>基本信息</span>
        </div>

        <el-form
          ref="productForm"
          :model="productForm"
          :rules="productRules"
          label-width="80px"
          class="action-form">

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-input
                  v-model="productForm.name"
                  placeholder="请输入商品名称"
                  maxlength="50"
                  show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品价格" prop="price">
                <div class="input-wrapper">
                  <el-input-number
                    v-model="productForm.price"
                    :min="0"
                    :precision="2"
                    placeholder="请输入商品价格"
                    style="width: 100%">
                  </el-input-number>
                  <span style="color: #909399; margin-left: 8px;">元</span>
                </div>
                <div class="form-tip">
                  <i class="el-icon-info"></i>
                  提交时价格会自动转换为分（元 × 100）
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库存数量" prop="num">
                <el-input-number
                  v-model="productForm.num"
                  :min="0"
                  placeholder="请输入库存数量"
                  style="width: 100%">
                </el-input-number>
                <div class="form-tip">
                  <i class="el-icon-info"></i>
                  库存大于0时商品自动上架，库存为0时自动下架
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品属性" prop="attribute">
                <el-input
                  v-model="productForm.attribute"
                  placeholder="请输入商品属性（如：颜色、尺寸等）"
                  maxlength="100"
                  show-word-limit>
                </el-input>
                <div class="form-tip">
                  <i class="el-icon-edit-outline"></i>
                  可填写商品的规格、颜色、尺寸等属性信息
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品描述">
            <el-input
              v-model="productForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入商品描述"
              maxlength="500"
              show-word-limit>
            </el-input>
            <div class="form-tip">
              <i class="el-icon-document"></i>
              详细描述商品的特点和用途，有助于用户了解商品
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 图片上传区域 -->
      <div class="form-section">
        <div class="section-title">
          <i class="el-icon-picture"></i>
          <span>商品图片</span>
        </div>

        <el-form
          ref="productForm"
          label-width="80px"
          class="action-form">
          <el-form-item label="上传图片">
            <el-upload
              ref="upload"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :file-list="fileList"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              list-type="picture-card"
              :limit="5"
              accept="image/*">
              <i class="el-icon-plus"></i>
            </el-upload>
            <div class="form-tip">
              <i class="el-icon-picture"></i>
              只能上传jpg/png文件，且不超过2MB，最多5张图片
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">
          <i class="el-icon-close"></i>
          取消
        </el-button>
        <el-button @click="resetProductForm">
          <i class="el-icon-refresh-left"></i>
          重置
        </el-button>
        <el-button
          type="primary"
          @click="handleSubmitProduct"
          :loading="submitting">
          <i class="el-icon-plus"></i>
          {{ submitting ? '添加中...' : '添加商品' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMerchantProductPage, getProductDetail, editProduct, addProduct } from '@/api/merchant/product-management'
import { getUserInfo, markCarousel } from '@/api/aggregation'
import { getToken } from '@/utils/auth'

export default {
  name: 'ProductManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        dateRange: []
      },

      // 表格数据
      productList: [],
      loading: false,

      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '商品ID', width: 80, align: 'center' },
        { prop: 'name', label: '商品名称', minWidth: 180, showOverflowTooltip: true },
        {
          prop: 'price',
          label: '商品价格',
          minWidth: 120,
          align: 'center',
          formatter: (row, column, cellValue) => {
            return `¥${this.formatPrice(cellValue)}`
          }
        },
        { prop: 'num', label: '库存数量', minWidth: 120, align: 'center', slot: 'num' },
        { prop: 'attribute', label: '商品属性', minWidth: 120, showOverflowTooltip: true },
        { prop: 'status', label: '状态', minWidth: 100, align: 'center', slot: 'status' },
        { label: '轮播图', minWidth: 100, align: 'center', slot: 'carousel' },
        {
          prop: 'createTime',
          label: '上架时间',
          minWidth: 160,
          align: 'center',
          formatter: (row, column, cellValue) => {
            return this.formatDateTime(cellValue)
          }
        },
        { label: '操作', minWidth: 140, align: 'center', fixed: 'right', slot: 'actions' }
      ],

      // 分页
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },

      // 详情对话框
      detailDialogVisible: false,
      selectedProduct: null,

      // 编辑商品对话框
      editDialogVisible: false,
      editLoading: false,
      editForm: {
        id: null,
        name: '',
        price: null,
        num: null,
        attribute: '',
        merchantId: null,
        status: null
      },
      editRules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 50, message: '商品名称长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', min: 1, message: '价格必须大于0', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入库存数量', trigger: 'blur' },
          { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
        ]
      },

      // 添加商品对话框
      addDialogVisible: false,
      submitting: false,
      productForm: {
        name: '',
        price: null,
        num: null,
        attribute: '',
        description: '',
        merchantId: null
      },
      fileList: [],
      uploadUrl: '/agg/file/upload',
      uploadHeaders: {
        'token': getToken()
      },
      productRules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 50, message: '商品名称长度在1到50个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', min: 0, message: '商品价格不能小于0', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入库存数量', trigger: 'blur' },
          { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
        ],
        attribute: [
          { max: 100, message: '商品属性长度不能超过100个字符', trigger: 'blur' }
        ]
      }
    }
  },

  mounted() {
    this.loadData()
  },

  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        // 调试用户状态
        Logger.log('=== 用户状态调试 ===')
        Logger.log('用户状态:', this.$store.state.user)
        Logger.log('用户ID:', this.$store.state.user.id)
        Logger.log('用户类型:', this.$store.state.user.userType)
        Logger.log("用户id",this.$store.state.userId)

        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size,
          name: this.searchForm.name || '',
          merchantId: this.$store.state.user.id // 根据接口文档，需要传递商家ID
        }

        Logger.log('=== 商家商品管理API请求调试 ===')
        Logger.log('请求参数:', params)

        const response = await getMerchantProductPage(params)
        Logger.log('商品列表响应:', response.data)

        if (response.code === 0 && response.data) {
          this.productList = response.data.list || []
          this.pagination.total = response.data.total || 0

          // 自动根据库存同步商品状态
          this.productList.forEach(product => {
            const expectedStatus = product.num > 0 ? 1 : 0 // 库存>0上架，库存=0下架
            if (product.status !== expectedStatus) {
              Logger.log(`商品 ${product.name} 状态不一致，库存:${product.num}，当前状态:${product.status}，应为:${expectedStatus}`)
              // 自动同步状态到后端
              this.autoSyncProductStatus(product.id, expectedStatus)
            }
          })

          Logger.log('商品列表加载成功，共', this.productList.length, '个商品')
        } else {
          this.productList = []
          this.pagination.total = 0
          if (response.data && response.data.msg) {
            Logger.log('商品查询结果:', response.data.msg)
          }
        }

      } catch (error) {
        Logger.error('加载商品数据失败:', error)
        this.productList = []
        this.pagination.total = 0
        this.$message.error('加载商品数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        name: '',
        dateRange: []
      }
      this.pagination.current = 1
      this.loadData()
    },

    // 添加商品 - 打开弹窗
    async handleAdd() {
      Logger.log('=== 打开添加商品弹窗 ===')
      Logger.log('用户状态:', this.$store.state.user)
      Logger.log('当前用户ID:', this.$store.state.user.id)
      // 获取商家ID
      try {
        const userId = this.$store.state.user.id

        if (!userId) {
          this.$message.error('无法获取用户ID，请重新登录')
          return
        }

        const response = await getUserInfo({ id: userId })
        Logger.log('用户详情响应:', response.data)

        if (response.code === 0 && response.data) {
          const merchantId = response.data.id
          this.productForm.merchantId = merchantId
          Logger.log('✅ 获取到商家ID:', merchantId)
        } else {
          this.productForm.merchantId = userId
          Logger.log('使用store中的用户ID:', userId)
        }
      } catch (error) {
        Logger.error('获取用户信息失败:', error)
        this.productForm.merchantId = this.$store.state.user.id
      }

      // 打开对话框
      this.addDialogVisible = true
    },

    // 查看详情
    async handleView(row) {
      try {
        const response = await getProductDetail(row.id)
        Logger.log('商品详情响应:', response.data)

        if (response.code === 0 && response.data) {
          this.selectedProduct = response.data
          this.detailDialogVisible = true
        } else {
          this.$message.error('获取商品详情失败')
        }
      } catch (error) {
        Logger.error('获取商品详情失败:', error)
        this.$message.error('获取商品详情失败')
      }
    },

    // 编辑商品
    async handleEdit(row) {
      try {
        Logger.log('=== 打开编辑商品对话框 ===')
        Logger.log('商品信息:', row)

        // 获取商品详情
        const response = await getProductDetail(row.id)
        Logger.log('商品详情响应:', response.data)

        if (response.code === 0 && response.data) {
          const productData = response.data

          // 填充编辑表单数据
          this.editForm = {
            id: productData.id,
            name: productData.name,
            price: productData.price,
            num: productData.num,
            attribute: productData.attribute || '',
            merchantId: productData.merchantId,
            status: productData.status
          }

          this.editDialogVisible = true
          Logger.log('编辑表单数据:', this.editForm)
        } else {
          this.$message.error('获取商品详情失败: ' + (response.data?.msg || '未知错误'))
        }
      } catch (error) {
        Logger.error('获取商品详情失败:', error)
        this.$message.error('获取商品详情失败')
      }
    },

    // 切换商品状态
    // 根据接口文档，ProductDTO没有status字段，暂时移除状态切换功能

    // 分页变化事件（统一处理）
    handlePageChange({ currentPage, pageSize }) {
      // 分页参数已经通过 .sync 自动更新，这里只需要重新加载数据
      this.loadData()
    },

    // 处理轮播开关变化
    async handleCarouselChange(product) {
      const originalValue = product.isCarousel
      try {
        Logger.log('=== 切换商品轮播状态 ===')
        Logger.log('商品ID:', product.id)
        Logger.log('新状态:', product.isCarousel)

        const response = await markCarousel({
          productId: product.id,
          isCarousel: product.isCarousel
        })

        if (response.code === 0) {
          this.$message.success(product.isCarousel === 1 ? '已添加到轮播' : '已从轮播移除')
        } else {
          // 失败则恢复开关状态
          product.isCarousel = originalValue === 1 ? 0 : 1
          this.$message.error(response.msg || '操作失败')
        }
      } catch (error) {
        Logger.error('切换轮播状态失败:', error)
        // 失败则恢复开关状态
        product.isCarousel = originalValue === 1 ? 0 : 1
        this.$message.error('操作失败')
      }
    },

    // 格式化价格
    formatPrice(price) {
      if (!price) return '0.00'
      return (price / 100).toFixed(2) // 假设后端存储的是分
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString()
    },

    // 获取状态类型（基于库存自动判断）
    getStatusType(status, num) {
      // 库存为0自动下架，库存>0自动上架
      if (num === 0) {
        return 'danger' // 下架
      } else {
        return 'success' // 上架
      }
    },

    // 获取状态文本（基于库存自动判断）
    getStatusText(status, num) {
      // 库存为0自动下架，库存>0自动上架
      if (num === 0) {
        return '已下架'
      } else {
        return '已上架'
      }
    },

    // 获取表格行类名
    getRowClassName({ row, rowIndex }) {
      if (row.num === 0) {
        return 'zero-stock-row'
      }
      return ''
    },

    // 商品状态现在完全由库存自动控制，无需手动切换

    // 自动同步商品状态（根据库存）
    async autoSyncProductStatus(productId, expectedStatus) {
      try {
        // 先获取商品详情，然后更新状态
        const detailResponse = await getProductDetail(productId)

        if (detailResponse.data && detailResponse.data.code === 0 && detailResponse.data.data) {
          const productData = detailResponse.data.data

          // 使用编辑商品接口更新状态
          const updateData = {
            id: productData.id,
            name: productData.name,
            price: productData.price,
            num: productData.num,
            attribute: productData.attribute || '',
            merchantId: productData.merchantId,
            status: expectedStatus // 更新状态
          }

          Logger.log('=== 自动同步商品状态 ===')
          Logger.log('商品ID:', productId, '目标状态:', expectedStatus)
          Logger.log('更新数据:', updateData)

          const response = await editProduct(updateData)

          if (response.code === 0) {
            Logger.log('商品状态自动同步成功')
            // 更新本地商品列表中的状态
            const product = this.productList.find(p => p.id === productId)
            if (product) {
              product.status = expectedStatus
            }
          } else {
            Logger.error('商品状态自动同步失败:', response.data?.msg)
          }
        } else {
          Logger.error('获取商品详情失败:', detailResponse.data?.msg)
        }
      } catch (error) {
        Logger.error('自动同步商品状态失败:', error)
      }
    },

    // 提交编辑商品
    async handleSubmitEdit() {
      try {
        // 表单验证
        await this.$refs.editForm.validate()

        this.editLoading = true

        // 准备提交数据
        const submitData = {
          id: this.editForm.id,
          name: String(this.editForm.name),
          price: Number(this.editForm.price),
          num: Number(this.editForm.num),
          attribute: String(this.editForm.attribute || ''),
          merchantId: Number(this.editForm.merchantId),
          status: Number(this.editForm.num) > 0 ? 1 : 0 // 根据库存自动设置状态
        }

        Logger.log('=== 编辑商品API请求调试 ===')
        Logger.log('提交数据:', submitData)

        const response = await editProduct(submitData)

        Logger.log('=== 编辑商品API响应 ===')
        Logger.log('响应数据:', response.data)

        if (response.code === 0) {
          this.$message.success('商品信息更新成功')
          this.editDialogVisible = false
          this.loadData() // 重新加载数据
        } else {
          this.$message.error('更新失败: ' + (response.data?.msg || '未知错误'))
        }
      } catch (error) {
        if (error.message) {
          // 表单验证错误
          return
        }
        Logger.error('=== 编辑商品失败 ===')
        Logger.error('错误信息:', error)
        this.$message.error('更新失败，请重试')
      } finally {
        this.editLoading = false
      }
    },

    // 提交添加商品
    async handleSubmitProduct() {
      try {
        // 表单验证
        await this.$refs.productForm.validate()

        this.submitting = true

        // 准备提交数据
        const submitData = {
          name: String(this.productForm.name),
          price: Number(this.productForm.price)*100,  //后台需要的金额单位为：分
          num: Number(this.productForm.num),
          attribute: String(this.productForm.attribute || ''),
          merchantId: Number(this.productForm.merchantId),
          status: Number(this.productForm.num) > 0 ? 1 : 0 // 库存>0自动上架，库存=0自动下架
        }

        Logger.log('=== 添加商品API请求调试 ===')
        Logger.log('提交数据:', submitData)
        Logger.log('数据类型检查:')
        Logger.log('- name类型:', typeof submitData.name, '值:', submitData.name)
        Logger.log('- price类型:', typeof submitData.price, '值:', submitData.price)
        Logger.log('- num类型:', typeof submitData.num, '值:', submitData.num)
        Logger.log('- attribute类型:', typeof submitData.attribute, '值:', submitData.attribute)
        Logger.log('- merchantId类型:', typeof submitData.merchantId, '值:', submitData.merchantId)

        const response = await addProduct(submitData)
        Logger.log('添加商品响应:', response.data)

        if (response.code === 0) {
          this.$message.success('商品添加成功')
          this.addDialogVisible = false
          this.resetProductForm()
          // 重新加载列表
          this.loadData()
        } else {
          this.$message.error(response.data?.msg || '商品添加失败')
        }

      } catch (error) {
        Logger.error('添加商品失败:', error)
        if (error.message) {
          this.$message.error(error.message)
        } else {
          this.$message.error('添加商品失败，请重试')
        }
      } finally {
        this.submitting = false
      }
    },

    // 重置商品表单
    resetProductForm() {
      if (this.$refs.productForm) {
        this.$refs.productForm.resetFields()
      }
      this.productForm = {
        name: '',
        price: null,
        num: null,
        attribute: '',
        description: '',
        merchantId: this.$store.state.user.id
      }
      this.fileList = []
    },

    // 关闭添加对话框
    handleAddDialogClose() {
      this.resetProductForm()
    },

    // 上传前验证
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!')
        return false
      }

      // 动态更新token，确保使用最新的token
      const token = getToken()
      if (token) {
        this.uploadHeaders['token'] = token
      } else {
        this.$message.error('请先登录!')
        return false
      }

      return true
    },

    // 上传成功
    handleUploadSuccess(response, file, fileList) {
      Logger.log('图片上传成功:', response)
      if (response && response.code === 0) {
        this.$message.success('图片上传成功')
        Logger.log('图片URL:', response.data)
      } else {
        this.$message.error(response?.msg || '图片上传失败')
      }
    },

    // 上传失败
    handleUploadError(error, file, fileList) {
      Logger.error('图片上传失败:', error)
      this.$message.error('图片上传失败')
    },

    // 移除文件
    handleRemove(file, fileList) {
      Logger.log('移除文件:', file)
      this.fileList = fileList
    }
  }
}
</script>

<style scoped>
.product-management-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 库存为0的商品样式 */
.zero-stock {
  color: #F56C6C;
  font-weight: bold;
}

/* 表格行样式 - 库存为0时整行高亮 */
.el-table .zero-stock-row {
  background-color: #FEF0F0;
}

.el-table .zero-stock-row:hover > td {
  background-color: #FEF0F0 !important;
}

/* 表格布局优化 */
.el-table {
  width: 100% !important;
  table-layout: auto !important;
}

.el-table .el-table__body-wrapper {
  width: 100% !important;
}

.el-table th,
.el-table td {
  padding: 12px 8px;
}

/* 确保表格占满容器宽度 */
.product-list .el-card__body {
  padding: 20px;
}

.product-list .el-table {
  margin: 0;
}

.page-header {
  margin-bottom: 20px;
}

.info-section {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
}

.page-description {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.product-list {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions .el-button {
  margin-left: 10px;
}

/* 分页样式由 ConfigurableTable 组件自动处理，无需额外样式 */

/* 弹框相关样式已由全局弹框样式管理，此处只保留必要的自定义样式 */

/* 响应式设计 */
@media (max-width: 768px) {
  .product-management-container {
    padding: 10px;
  }

  .page-title {
    font-size: 20px;
  }

  .el-col {
    margin-bottom: 10px;
  }
}

</style>
